import serial
from loguru import logger
from .config import *


class Relay:
    def __init__(self, serial_port: str, rate: int):
        self.serial_port = serial_port
        self.rate = rate
        self.ser = serial.Serial(serial_port, rate)

    def read(self, channel: int) -> bool:
        if self.ser.is_open:
            logger.info(f'串口{self.serial_port}已打开')
            self.ser.write(bytes.fromhex(f'ff'))
            result = self.ser.read(40).decode().split('\r\n')[:4][channel - 1]
            result = result.split(':')[1].strip()
            if result == 'ON':
                return True
            else:
                return False
        else:
            logger.warning(f'串口{self.serial_port}未打开')
            return False

    def open_relay(self, channel: int):
        if self.ser.is_open:
            while True:
                self.ser.write(bytes.fromhex(f'a0 0{channel} 01 a{channel + 1}'))
                r = self.read(channel)
                if r:
                    logger.info(f'通道{channel}已打开')
                    break
                else:
                    logger.warning(f'通道{channel}未打开')
                    continue
        else:
            logger.warning(f'串口{self.serial_port}未打开')

    def close_relay(self, channel: int):
        if self.ser.is_open:
            logger.info(f'串口{self.serial_port}已打开')
            while True:
                self.ser.write(bytes.fromhex(f'a0 0{channel} 00 a{channel}'))
                r = self.read(channel)
                if not r:
                    logger.info(f'通道{channel}已关闭')
                    break
                else:
                    logger.warning(f'通道{channel}未关闭')
                    continue

        else:
            logger.info(f'串口{self.serial_port}未打开')

    def close(self):
        self.ser.close()


if __name__ == '__main__':
    logger.add('run.log')
    c = Config(r'/config.ini')
    Relay(c['Relay', 'port'], int(c['Relay', 'rate'])).open_relay(3)
    # Relay('COM5', 9600).read(3)
